<template>
  <div class="number-input" :class="{ disable: disable }">
    <div @click="jian" class="jian" :class="{ dis: number == 1 }">-</div>
    <input type="number" v-model="number" :disabled="disable" />
    <div @click="add" class="add" :class="{ dis: number >= max }">+</div>
  </div>
</template>

<script>
export default {
  name: "NumberInput1",
  props: {
    num: Number,
    max: Number,
    disable: Boolean,
  },
  model: {
    prop: "num",
    event: "change",
  },
  data() {
    return {
      number: 1,
    };
  },
  watch: {
    num() {
      this.number = this.num;
    },
    number() {
      if (!this.max) return;
      let num = parseInt(this.number);
      if (num >= 1) {
        if (this.max && num <= this.max) {
          this.$emit("change", num);
        } else {
          this.$emit("change", this.max);
        }
      } else this.$emit("change", 1);
    },
  },
  created() {
    this.number = this.num;
  },
  methods: {
    jian() {
      if (this.disable) return;
      let num = parseInt(this.number) - 1;
      if (num > 1) {
        this.$emit("change", num);
      } else {
        this.$emit("change", 1);
      }
    },
    add() {
      if (this.disable) return;
      let num = parseInt(this.number) + 1;
      if (this.max && num <= this.max) {
        this.$emit("change", num);
      } else {
        this.$emit("change", this.max);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.number-input {
  width: 116px;
  height: 26px;
  border-radius: 5px;
  border: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  &.disable {
    opacity: 0.8;
  }
  .jian,
  .add {
    width: 30px;
    height: 26px;
    background: #e7e7e7;
    border-radius: 4px 0px 0px 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    &.dis {
      background: none;
    }
  }
  input {
    background: none;
    flex: 1;
    width: 0;
    border: 0;
    padding: 0 6px;
    text-align: center;
  }
}
</style>
